--- 肯特 插入式电磁流量计
module(..., package.seeall)

local dtu, udtu = {}, {} -- 配置文件
local meter_ins, meter_val, addr
function setDtu(_dtu, _udtu)
    dtu, udtu = _dtu, _udtu
    addr = udtu.addr and tonumber(udtu.addr) or 1
    sys.taskInit(init)
end

local function _pro(d)
    if #d == 15 then
        local _, ins = pack.unpack(d:sub(4, 7), ">f")
        meter_ins = string.format("%.2f", ins)
        local v_hex = d:sub(10, 13)
        meter_val = tonumber(v_hex:toHex(), 16)
        usrdata.update({ meter_val, meter_ins })
        if lcd.LCD_DATA[3]:match('累计(.+)') then
            lcd.LCD_DATA[3] = '瞬时:' .. (meter_ins or "NULL")
            return
        end
        lcd.LCD_DATA[3] = '累计:' .. (meter_val or "NULL")
    end
end
function init()
    power.openBoost()
    sys.wait(200)
    while true do
        tools.modbus_send(3, addr, 3, 0, 5)
        local result, d = sys.waitUntil("UART_READ_DONE_NEXT_3", 5000)
        if result then
            if d then
                _pro(d)
            end
            sys.wait(5000)
        else
            lcd.LCD_DATA[3] = " READ TIMEOUT"
        end
    end
end
